<?php

namespace App\Services\Cache;

use App\Models\BlindBox;
use App\Models\BlindBoxCategory;
use App\Models\BlindBoxLevelValue;
use App\Models\BlindBoxProduct;
use App\Models\BlindBoxOrder;
use Illuminate\Support\Facades\Cache;
use App\Http\Controllers\Api\V1\Queries\ProductQuery;

class BlindBoxCache
{
	
	public function box($id)
	{
		$key = url()->full();
		$box = Cache::remember($key, 1, function () use ($id) {
			return BlindBox::query()->findOrFail($id);
		});
		return $box;
	}
	
	public function levels($id)
	{
		$key = url()->full();
		$levels = Cache::remember($key, 1, function () use ($id) {
			$levels = BlindBoxLevelValue::query()
						->join('blind_box_levels','blind_box_levels.id','blind_box_level_values.blind_box_level_id')
						->used()
						->where('blind_box_id',$id)
						->orderBy("blind_box_levels.order")
						->get();
			
			return $levels;
		
		});
		return $levels;
	}

	public function takeOrders($id)
	{
		$key = url()->full();
		$orders = Cache::remember($key, 1, function () use ($id) {
			$orders = BlindBoxOrder::query()
						->paid()
						->where('is_taken',true)
						->where('blind_box_id',$id)
						->orderBy("id",'desc')
						->paginate();
			
			return $orders;
		
		});
		return $orders;
	}

	public function products($id)
	{
		$key = url()->full();
		$products = Cache::remember($key, 1, function () use ($id) {
			$products = BlindBoxProduct::query()
						->join('blind_box_levels','blind_box_levels.id','blind_box_products.blind_box_level_id')
						->join('blind_box_level_values', function ($join) {
						 	 $join->on('blind_box_level_values.blind_box_level_id', '=','blind_box_products.blind_box_level_id')
						 	 	->on('blind_box_products.blind_box_id', '=','blind_box_level_values.blind_box_id');
						 })
						->with('product')
						->where('blind_box_products.blind_box_id',$id)
						->where('blind_box_level_values.is_used',true)
						->orderBy("blind_box_products.id")
						->paginate();
			
			return $products;
		
		});
		return $products;
	}

	public function boxes()
	{
		$categoryId  =  request('category_id');
		$blindBoxCategoryId  =  request('blind_box_category_id');
		

		$key = url()->full();
		$boxes = Cache::remember($key, 1, function () use ($categoryId, $blindBoxCategoryId) {
			if(!$blindBoxCategoryId){
				if($categoryId){
					$blindBoxCategory =  BlindBoxCategory::where("category_id",$categoryId)->first();
						$blindBoxCategoryId = $blindBoxCategory->id;
				}else{
					$blindBoxCategoryId = 0;
				}

			}
			
			return app(BlindBox::class)
				->where('blind_box_category_id' , $blindBoxCategoryId)
				->orderBy('id')
				->paginate();
		});
		return $boxes;
	}

	
}
